from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
import sqlite3
import hashlib

DB_PATH = 'projmate.db'
router = APIRouter()

class LoginRequest(BaseModel):
    username: str
    password: str

class TokenResponse(BaseModel):
    token: str

def get_db():
    conn = sqlite3.connect(DB_PATH)
    try:
        yield conn
    finally:
        conn.close()

def hash_password(password: str) -> str:
    return hashlib.sha256(password.encode('utf-8')).hexdigest()

@router.post("/login", response_model=TokenResponse)
def login(data: LoginRequest, db=Depends(get_db)):
    cur = db.cursor()
    cur.execute("SELECT password FROM user WHERE username=?", (data.username,))
    row = cur.fetchone()
    if not row:
        raise HTTPException(status_code=401, detail="用户名不存在")
    hashed = row[0]
    if hash_password(data.password) != hashed:
        raise HTTPException(status_code=401, detail="密码错误")
    token = hashlib.md5(f"{data.username}:{hashed}".encode()).hexdigest()
    return {"token": token} 